package top.roadvast.pd.componnent;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.roadvast.pd.bean.PdOrder;
import top.roadvast.pd.service.OrderService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 20:50
 * @Version 1.0
 * @Description rabbitmq监听器
 */
@Component
@Slf4j
public class OrderConsumer {
    //收到订单数据后,会调用订单的业务代码,把订单保存到数据库
    @Resource
    OrderService orderService;

    //添加该注解后,会从指定的orderQueue接收消息,
    //并把数据转为 PdOrder 实例传递到此方法
    @RabbitListener(queues = "order_queue")
    public void save(PdOrder  order, Channel channel, Message message) {
        try {
            log.info("接收到订单，开始进行处理...");
            log.info("订单信息：" + order);
            orderService.saveOrder(order);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
